package com.mitu.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

//BIO模型服务器端
public class BIOServer {
    public static void main(String[] args) throws IOException {
        //创建一个线程池
        ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();
        //创建一个ServerSocket,端口为6666
        ServerSocket serverSocket = new ServerSocket(6666);
        System.out.println("服务器启动了...");
        while (true) {
            System.out.println("线程信息 id =" + Thread.currentThread().getId() + "-线程名:" + Thread.currentThread().getName());
            //进行监听，等待客户端的连接
            final Socket socket = serverSocket.accept();
            System.out.println("连接到一个客户端...");
            //创建一个线程与之通信
            newCachedThreadPool.execute(() -> {
                //可以和客户端通讯
                handler(socket);
            });
        }
        //如果有客户端连接，就创建一个线程与之通信
    }

    //编写一个handler方法。和客户端通讯
    public static void handler(Socket socket) {
        try {
            System.out.println("线程信息 id =" + Thread.currentThread().getId() + "-线程名:" + Thread.currentThread().getName());
            byte[] buffer = new byte[1024];
            //通过socket获取输入流读取数据
            InputStream inputStream = socket.getInputStream();
            //循环读取客户端发送的数据
            while (true) {
                System.out.println("线程信息 id =" + Thread.currentThread().getId() + "-线程名:" + Thread.currentThread().getName());
                int read = inputStream.read(buffer);  //返回值为读取的数据量
                if (read != -1) {
                    //还可以继续读
                    System.out.println(new String(buffer, 0, read));   //输出客户端发送的数据
                } else {
                    //说明读取完毕
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            System.out.println("关闭和客户端的连接");
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
